<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>Websocket</title>
    <link rel="stylesheet" th:href="@{/lib/layui/css/layui.css}" media="all">
    <link rel="stylesheet" th:href="@{/css/public.css}" media="all">
    <style>
        .layui-form-item .layui-input-company {
            width: auto;
            padding-right: 10px;
            line-height: 38px;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <form class="layui-form" action="" lay-filter="formDemo">
            <div class="layui-form layuimini-form">
                <div class="layui-form-item">
                    <label class="layui-form-label required">内容</label>
                    <div class="layui-input-block">
                        <input type="text" name="content" placeholder="请输入" class="layui-input" lay-verify="required">
                        <tip id="tip"></tip>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-submit lay-filter="saveBtn"> 发送
                        </button>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block" id="message">

                    </div>
                </div>
            </div>
        </form>

        <form class="layui-form" action="" lay-filter="formDemo1">
            <div class="layui-form layuimini-form">
                <div class="layui-form-item">
                    <label class="layui-form-label required">接收人id</label>
                    <div class="layui-input-block">
                        <input type="text" name="receiveUser" placeholder="请输入" class="layui-input" lay-verify="required">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label required">内容</label>
                    <div class="layui-input-block">
                        <input type="text" name="content" placeholder="请输入" class="layui-input" lay-verify="required">
                        <tip id="tip1"></tip>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-submit lay-filter="saveBtn1"> 发送 </button>
                    </div>
                </div>
            </div>
        </form>

    </div>
</div>

<script th:src="@{/lib/jquery-3.4.1/jquery-3.4.1.min.js}" charset="utf-8"></script>
<script th:src="@{/lib/coco-message/coco-message.js}" charset="utf-8"></script>
<script th:src="@{/lib/layui/layui.js}" charset="utf-8"></script>
<script th:src="@{/js/lay-config.js}" charset="utf-8"></script>
<script type="text/javascript" th:inline="javascript">
    AjaxUtil.ctx = /*[[@{/}]]*/'';
    layui.use(['form', 'layNotify'], function () {
        var form = layui.form,
            layer = layui.layer,
            layNotify = layui.layNotify;

        // websocket对象
        var websocket = null;
        // 判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            var url = [[${url}]];
            websocket = new WebSocket(url.replace('${host}', window.location.host));
        } else {
            layer.alert('当前浏览器不支持开启会话！');
        }
        // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            websocket.close();
        };
        var index = 0;
        // 监听消息接收
        websocket.onmessage = function (event) {
            console.log(event);
            layNotify.notice({
                title: "你有新的消息",
                type: "success",
                message: event.data
            });
            if (0 == index) {
                $('#tip').text(event.data);
                index++;
            } else {
                $('#message').append('<br/><tip>您收到的内容：' + event.data + '</tip>');
            }
        };


        // 监听提交
        form.on('submit(saveBtn)', function (res) {
            var data = res.field;
            // 发送消息
            websocket.send(data.content);
            form.val("formDemo", {
                content: ''
            });
            $('input[name="content"]').focus();
            return false;
        });

        // 监听提交
        form.on('submit(saveBtn1)', function (res) {
            var data = res.field;

            AjaxUtil.post({
                url: AjaxUtil.ctx + "websocket/sendMessage",
                data: JSON.stringify(data),
                contentType: 'application/json',
                success: function (res) {
                    if (res.code === 0) {
                        console.log(res);
                    } else {
                        layer.close(loading);
                        Message.error(res.message, 1000);
                    }
                },
                error: function (error) {
                }
            });

            return false;
        });
    });
</script>
</body>
</html>